/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 *
 * @author aaron
 */
public class LogClient {
    public static final String LOGGER_NAME = "JHaveSocketLogger";
    public static final String RELOGGER_NAME = "JHaveSocketReLogger";
    protected static final Logger logger = Logger.getLogger(LOGGER_NAME);
    protected static final Logger relogger = Logger.getLogger(RELOGGER_NAME);

    static {
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        LogManager.getLogManager().addLogger(logger);

        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
    }

    public static void addLoggerHandler(String host, int port, String serverId) throws IOException {
            logger.addHandler(new JHaveSocketHandler(host, port, serverId, false));
            relogger.addHandler(new JHaveSocketHandler(host, port, serverId, true));
    }

    public static Logger getLogger() {
        return logger;
    }

    public static Logger getReLogger() {
        return relogger;
    }

    public static void log(Level level, String message) {
        logger.log(level, message);
    }

    public static void reLog(String message) {
        relogger.log(Level.INFO, message);
    }


    static BufferedReader br = null;
    static String myServerId = null;
    static Random r = new Random(new Date().getTime());
    static String serverIP = null;

    public static void main(String[] args) throws IOException, InterruptedException {
        if(args.length > 0) {
            myServerId = args[0];
        } else {
            myServerId = Integer.toString(Math.abs(r.nextInt()));
        }
        if(args.length > 1){
            serverIP = args[1];
        }else{
            serverIP = "127.0.0.1";
        }
        br = new BufferedReader(new InputStreamReader(System.in));

        LogClient.addLoggerHandler(serverIP, 8190, myServerId);

        Thread.sleep(50);

        while(checkShouldContinueReading()) {
            String line = br.readLine();
            LogClient.reLog(line);
        }

        br.close();
    }

    protected static boolean checkShouldContinueReading() throws IOException, InterruptedException {
        if(br.ready() || System.in.available() > 0) {
            return true;
        } else {
            Thread.sleep(10);
            if(br.ready() || System.in.available() > 0) {
                return true;
            } else {
                return false;
            }
        }
    }
}
